﻿#region 作者和版权
/*************************************************************************************
      * CLR 版本:       4.0.30319.225
      * 类 名 称:       Input
      * 机器名称:       LIRONGNAN
      * 命名空间:       LCL.Common
      * 文 件 名:       Input
      * 创建时间:       2013 2013-10-13 23:25:42
      * 作    者:       李荣楠
      * 版    权:       Input说明：本代码版权归李荣楠所有，请勿商用 2013 - 2014    
      * 修改时间:
      * 修 改 人:
      ************************************************************************************/
#endregion

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using LCL.Config;

namespace LCL.Common
{
    /// <summary>
    /// 摘要
    /// </summary>
    public class Input
    {
        #region 私有成员

        #endregion

        #region 属性

        #endregion

        #region 方法

        #region MD5加密
        /// <summary>
        /// MD5加密字符串处理
        /// </summary>
        /// <param name="Half">加密是16位还是32位；如果为true为16位</param>
        public static string MD5(string Input, bool Half)
        {
            string output = FormsAuthentication.HashPasswordForStoringInConfigFile(Input, "MD5").ToLower();
            if (Half) output = output.Substring(8, 16);
            return output;
        }
        /// <summary>
        /// MD5加密字符串处理
        /// </summary>
        public static string MD5(string Input)
        {
            return MD5(Input, true);
        }
        #endregion

        #region DES加解密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="input">待加密的字符串</param>
        /// <param name="key">加密密钥</param>
        /// <returns></returns>
        public static string Encrypt(string EncryptString, byte[] Key, byte[] IV)
        {
            //byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] inputByteArray = Encoding.UTF8.GetBytes(EncryptString);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="input">待解密的字符串</param>
        /// <param name="key">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
        public static string Decrypt(string DecryptString, byte[] Key, byte[] IV)
        {
            try
            {
                //byte[] rgbKey = Encoding.UTF8.GetBytes(Key);
                byte[] inputByteArray = Convert.FromBase64String(DecryptString);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 路径处理
        /// <summary>
        /// 获取请求页面对应的类名
        /// </summary>
        /// <returns></returns>
        public static string GetClassName()
        {
            //获取请求页面物理路径
            string physicalPath = HttpContext.Current.Request.PhysicalPath;
            //获取系统运行根目录
            string physicalApplicationPath = HttpContext.Current.Request.PhysicalApplicationPath;
            return physicalPath.Replace(physicalApplicationPath, string.Empty).Replace(UiConfig.ExName, string.Empty).Replace(".aspx", string.Empty);
        }
        /// <summary>
        /// 获取要访问的实际文件名
        /// </summary>
        /// <returns></returns>
        public static string GetWebFileName()
        {
            return GetClassName().Replace(".", "/") + UiConfig.ExName;
        }
        //获取网站程序虚拟路径
        public static string GetApplicationPath()
        {
            string str = HttpContext.Current.Request.ApplicationPath;
            if (str == "/")
            {
                return string.Empty;
            }
            return str;
        }
        #endregion

        #region URL编码
        /// <summary>
        /// URL地址编码
        /// </summary>
        /// <param name="Input">输入字符串</param>
        /// <returns>返编码后的字符串</returns>
        public static string URLEncode(string Input)
        {
            if (string.IsNullOrEmpty(Input)) return string.Empty;
            else
                return HttpContext.Current.Server.UrlEncode(Input);
        }

        /// <summary>
        /// URL地址解码
        /// </summary>
        /// <param name="Input">输入字符串</param>
        /// <returns>返回解码后的字符串</returns>
        public static string URLDecode(string Input)
        {
            if (!string.IsNullOrEmpty(Input))
            {
                return HttpContext.Current.Server.UrlDecode(Input);
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion

        #region Request操作类
        /// <summary>
        /// 获得指定Url或表单参数的int类型值, 先判断Url参数是否为缺省值, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">Url或表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url或表单参数的int类型值</returns>
        public static int GetInt(string strName, int defValue)
        {
            if (GetQueryInt(strName, defValue) == defValue)
            {
                return GetFormInt(strName, defValue);
            }
            else
            {
                return GetQueryInt(strName, defValue);
            }
        }
        /// <summary>
        /// 获得指定表单参数的int类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的int类型值</returns>
        public static int GetFormInt(string strName, int defValue)
        {
            return Utils.StrToInt(HttpContext.Current.Request.Form[strName], defValue);
        }
        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static int GetQueryInt(string strName, int defValue)
        {
            return Utils.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);
        }
        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.Form[strName];
        }
        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.QueryString[strName];
        }
        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName)
        {
            if ("".Equals(GetQueryString(strName)))
            {
                return GetFormString(strName);
            }
            else
            {
                return GetQueryString(strName);
            }
        }
        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }
        #endregion

        #region Cookie操作类
        /// <summary>
        /// 设置登录的Cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="Password">已Md5加密后的密码</param>
        /// <param name="isAlways">是否保持登录状态(下次同一计算机免登录)</param>
        static public void SetCookie(string userId, string userName, string Password, bool isAlways)
        {
            SetCookie(userId, userName, Password, isAlways, UiConfig.CookieDomain);
        }
        /// <summary>
        /// 设置登录的Cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="Password">已Md5加密后的密码</param>
        /// <param name="isAlways">是否保持登录状态(下次同一计算机免登录)</param>
        static public void SetCookie(string userId, string userName, string Password, bool isAlways, bool isAdmin)
        {
            SetCookie(userId, userName, Password, isAlways, UiConfig.CookieDomain,isAdmin);
        }

        /// <summary>
        /// 设置登录的Cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="Password">已Md5加密后的密码</param>
        /// <param name="isAlways">是否保持登录状态(下次同一计算机免登录)</param>
        /// <param name="cookiesdomain">cookies域</param>
        static public void SetCookie(string userId, string userName, string Password, bool isAlways, string cookiesdomain)
        {
            SetCookie(userId, userName, Password, isAlways, cookiesdomain, false);
        }

        /// <summary>
        /// 设置登录的Cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="Password">已Md5加密后的密码</param>
        /// <param name="isAlways">是否保持登录状态(下次同一计算机免登录)</param>
        /// <param name="cookiesdomain">cookies域</param>
        /// <param name="isadmin">是否管理员登录</param>
        static public void SetCookie(string userId, string userName, string Password, bool isAlways, string cookiesdomain, bool isadmin)
        {
            string cookiesFlag = UiConfig.UsersCookiesFlag;
            if (isadmin)
                cookiesFlag = UiConfig.AdminCookiesFlag;
            HttpCookie SNSToKenCookie = new HttpCookie(cookiesFlag);
            //string s = userId.ToString() + SecretConfig.UserSeparator.ToString() + Password + SecretConfig.UserSeparator.ToString() + Public.GetClientIP() + SecretConfig.UserSeparator.ToString() + Input.MD5(UiConfig.CookieVerifyCode, false);
            string s = userId.ToString() + SecretConfig.UserSeparator.ToString() + Password + SecretConfig.UserSeparator.ToString()  + SecretConfig.UserSeparator.ToString() + Input.MD5(UiConfig.CookieVerifyCode, false);
            SNSToKenCookie["token"] = Encrypt(s, SecretConfig.UserKey, SecretConfig.UserIV);
            SNSToKenCookie["username"] = Input.URLEncode(userName);
            SNSToKenCookie.Domain = cookiesdomain;
            SNSToKenCookie.Secure = false;
            if (isadmin)
            {
                SNSToKenCookie["isAdminLogin"] = Input.URLEncode("true");
            }
            else
            {
                if (isAlways)
                {
                    SNSToKenCookie.Expires = DateTime.Now.AddYears(1);
                }
            }
            HttpContext.Current.Response.AppendCookie(SNSToKenCookie);
        }
        /// <summary>
        /// 清除cookies
        /// </summary>
        /// <param name="isAdmin">是否是管理员，0不是管理员，1是管理员</param>
        public void clearCookies(int isAdmin)
        {
            if (isAdmin==0)
            {
                 HttpCookie SNSToKenCookie = HttpContext.Current.Request.Cookies[UiConfig.UsersCookiesFlag];
            if (SNSToKenCookie != null)
            {
                SNSToKenCookie.Values.Clear();
                SNSToKenCookie.Domain = LCL.Config.UiConfig.CookieDomain;
                SNSToKenCookie.Expires = Convert.ToDateTime(DateTime.Now).AddDays(-1);
                HttpContext.Current.Response.SetCookie(SNSToKenCookie);
            }
            }
            else
            {
                HttpCookie SNSToKenCookie1 = HttpContext.Current.Request.Cookies[UiConfig.AdminCookiesFlag];
                if (SNSToKenCookie1 != null)
                {
                    SNSToKenCookie1.Values.Clear();
                    SNSToKenCookie1.Domain = LCL.Config.UiConfig.CookieDomain;
                    SNSToKenCookie1.Expires = Convert.ToDateTime(DateTime.Now).AddDays(-1);
                    HttpContext.Current.Response.SetCookie(SNSToKenCookie1);
                }
            }
           
          
        }
        #endregion
        #endregion

    }
}
